﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    class WorkspaceFolderIcon
    {
        internal static void RefreshWorkspaceFolderIcon()
        {
            try
            {
                SetWorkspaceFolderIcon();
            }
            catch (Exception ex)
            {
                LMessageBox.ShowWarning("未能顺利设置工作区文件夹的图标。错误消息如下：\r\n\r\n　　" + ex.Message);
                return;
            }
        }

        #region 设置文件夹图标

        /// Changed From:
        /// https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/92e3dca2-4e55-4bd4-be7a-ace4b8f90d1a/folder-icon-change-issue-windows-application-c?forum=windowsgeneraldevelopmentissues
        /// <param name="workspaceFullPath">默认情况下是当前工作区目录。</param>
        internal static UInt32 SetWorkspaceFolderIcon(string workspaceFullPath = null)
        {
            LPSHFOLDERCUSTOMSETTINGS FolderSettings = new LPSHFOLDERCUSTOMSETTINGS();
            FolderSettings.dwMask = 0x10;
            FolderSettings.pszIconFile = Globals.InstalledPath + "WorkspaceIcon.ico";  //@"D:\My Pictures\testImg\IconPack\ICO\BlankFolder.ico";

            FolderSettings.iIconIndex = 0;

            UInt32 FCS_READ = 0x00000001;
            UInt32 FCS_FORCEWRITE = 0x00000002;
            UInt32 FCS_WRITE = FCS_READ | FCS_FORCEWRITE;

            string pszPath = (string.IsNullOrEmpty(workspaceFullPath) ? Globals.PathOfWorkspace : workspaceFullPath);  // @"G:\FreeZone\New folder\New folder";
            string iniFilePath = pszPath + (pszPath.EndsWith("\\") ? "desktop.ini" : "\\desktop.ini");
            if (File.Exists(iniFilePath))
            {
                File.Delete(iniFilePath);
            }

            UInt32 HRESULT = SHGetSetFolderCustomSettings(ref FolderSettings, pszPath, FCS_WRITE);
            return HRESULT;
        }

        [DllImport("Shell32.dll", CharSet = CharSet.Auto)]
        static extern UInt32 SHGetSetFolderCustomSettings(ref LPSHFOLDERCUSTOMSETTINGS pfcs, string pszPath, UInt32 dwReadWrite);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct LPSHFOLDERCUSTOMSETTINGS
        {
            public UInt32 dwSize;
            public UInt32 dwMask;
            public IntPtr pvid;
            public string pszWebViewTemplate;
            public UInt32 cchWebViewTemplate;
            public string pszWebViewTemplateVersion;
            public string pszInfoTip;
            public UInt32 cchInfoTip;
            public IntPtr pclsid;
            public UInt32 dwFlags;
            public string pszIconFile;
            public UInt32 cchIconFile;
            public int iIconIndex;
            public string pszLogo;
            public UInt32 cchLogo;
        }
    }
    #endregion
}
